package com.suypower.carManage.comm;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by zhaoyuan on 14-2-17.
 */
public class UserLoginFilter implements Filter{

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        ServletResponse response = (ServletResponse) arg1;
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        String userid = (String) session.getAttribute("userid");
        if (userid == null || userid.equals("")) {
            response.getWriter().print("<html><head></head><body><script>location.href='"+basePath+"static/login/login.jsp'</script></body></html>");
            response.getWriter().close();
        } else {
            chain.doFilter(arg0, arg1);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
